package jjn.carl.linkedlist;

import commons.ListNode;

/**
 * @author Jiang Jining
 * @since 2023-07-02 22:32
 */
public class LeetCode142 {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head.next, slow = head;
        while (true) {
            if (fast == null || fast.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                break;
            }
        }
        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
